<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $captcha = $_POST['captcha'];
    
    // 验证验证码
    if ($captcha != $_SESSION['captcha']) {
        header("Location: login.php?error=2");
        exit();
    }
    
    // 读取用户数据
    $usersData = file_get_contents('user.txt');
    $users = json_decode($usersData, true);
    
    $authenticated = false;
    $userExists = false;
    
    // 检查用户是否存在且密码正确
    foreach ($users['users'] as $user) {
        if ($user['username'] === $username) {
            $userExists = true;
            if ($user['password'] === $password) {
                // 只允许tanbaolong登录
                if ($username === 'tanbaolong') {
                    $authenticated = true;
                    $_SESSION['username'] = $username;
                    header("Location: index.php");
                    exit();
                }
            }
        }
    }
    
    // 如果认证失败，返回登录页面并显示错误信息
    if (!$authenticated) {
        header("Location: login.php?error=1");
        exit();
    }
}
?> 